package com.gs.api.util.http;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;

/**
 * @author guoyunfei on 2021/7/5 20:52
 * @className HttpUtilDown
 * @description TODO
 * @Version 1.0
 */
public class HttpUtilDown {


    /**
     * 传入要下载的图片的url列表，将url所对应的图片下载到本地
     */
    public static void downloadPicture(Object urlString, String imagePath, String name) throws RuntimeException {

        File file = new File(imagePath);
        if (!file.exists()) {
            file.mkdirs();
        }

        if (urlString == null) {
            throw new RuntimeException("下载图片地址为空");
        }
        URL url = null;
        try {
            url = new URL(urlString.toString());

            DataInputStream dataInputStream = new DataInputStream(url.openStream());
            FileOutputStream fileOutputStream = new FileOutputStream(new File(imagePath + File.separator + name));

            byte[] buffer = new byte[1024];
            int length;

            while ((length = dataInputStream.read(buffer)) > 0) {
                fileOutputStream.write(buffer, 0, length);
            }

            dataInputStream.close();
            fileOutputStream.close();
        } catch (MalformedURLException e) {
            e.printStackTrace();
            throw new RuntimeException("下载、保存图片失败" + urlString);
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("保存图片失败" + urlString);
        }
    }

    /**
     * 传入要下载的图片的url列表，将url所对应的图片下载到本地
     *
     * @param urlList
     */
    private void downloadPicture(ArrayList<String> urlList,String path) {
        URL url = null;
        int imageNumber = 100;

        for (String urlString : urlList) {
            try {
                url = new URL(urlString);
                DataInputStream dataInputStream = new DataInputStream(url.openStream());
                String imageName = path + imageNumber + ".jpg";
                FileOutputStream fileOutputStream = new FileOutputStream(new File(imageName));

                byte[] buffer = new byte[1024];
                int length;

                while ((length = dataInputStream.read(buffer)) > 0) {
                    fileOutputStream.write(buffer, 0, length);
                }

                dataInputStream.close();
                fileOutputStream.close();
                imageNumber++;
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
